<template>
  <basic-container>
    <el-form
      ref="form"
      label-width="120px"
      style="display: flex; flex-wrap: wrap"
    >
      <span style="font-size: 24px;">标签：{{((tags == null || tags == '')?'空':tags)}}</span>
      <el-form-item label="更新时间:">
        <el-date-picker
          id="id-creativerepost-componets-creativePerformanceOnTag-isShowSelectOptions"
          size="mini"
          v-model="value1"
          type="daterange"
          value-format="yyyy-MM-dd"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          ref="performTime" @visible-change="isShowSelectOptions" @change="submitForm">
        </el-date-picker>
      </el-form-item>
      <!--<el-form-item tyle="width: 280px" label="提交人:">-->
        <!--<el-select v-if="!isAdvSharedOffer"-->
          <!--size="mini"-->
          <!--v-model="form.createUser"-->
          <!--placeholder="请选择提交人"-->
          <!--clearable-->
          <!--ref="performCreateUser" @visible-change="isShowSelectOptions" @change="submitForm">-->
          <!--<el-option-->
            <!--v-for="item in submitterList"-->
            <!--:key="item.submitterList"-->
            <!--:label="item.label"-->
            <!--:value="item.value"-->
          <!--&gt;-->
          <!--</el-option>-->
        <!--</el-select>-->
        <!--<el-select v-if="isAdvSharedOffer"-->
          <!--size="mini"-->
          <!--v-model="form.agencyTenantIdList"-->
          <!--placeholder="请选择提交人"-->
          <!--multiple filterable-->
          <!--clearable-->
        <!--&gt;-->
          <!--<el-option-->
            <!--v-for="item in agencyTenantList"-->
            <!--:key="item.agencyTenantId"-->
            <!--:label="item.tenantName"-->
            <!--:value="item.agencyTenantId"-->
          <!--&gt;-->
          <!--</el-option>-->
        <!--</el-select>-->
      <!--</el-form-item>-->
      <el-form-item tyle="width: 280px" label="媒体:">
        <el-select
          id="id-creativerepost-componets-creativePerformanceOnTag-platformList"
          size="mini"
          v-model="form.platform"
          placeholder="请选择媒体"
          clearable
          ref="performPlatform" @visible-change="isShowSelectOptions" @change="submitForm">
          <el-option
            v-for="item in platformList"
            :key="item.dictKey"
            :label="item.dictValue"
            :value="item.dictKey"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <!--<el-form-item tyle="width: 280px" label="素材名称:">-->
        <!--<el-input-->
          <!--size="mini"-->
          <!--v-model="form.name"-->
          <!--placeholder="请输入素材名称"-->
          <!--@keyup.enter.native="submitForm"></el-input>-->
      <!--</el-form-item>-->
      <el-form-item style="width: 280px">
        <el-button
          id="id-creativerepost-componets-creativePerformanceOnTag-submitForm"
          size="mini"
          type="primary"
          icon="el-icon-search"
          @click="submitForm"
          >搜索</el-button
        >
        <el-button id="id-creativerepost-componets-creativePerformanceOnTag-resetSearch"
                   size="mini" icon="el-icon-delete" @click="resetSearch"
          >清空</el-button
        >
      </el-form-item>
    </el-form>
    <avue-crud
      :option="option"
      :table-loading="loading"
      :data="data"
      :page.sync="page"
      v-model="form"
      ref="crud"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
      @sort-change="sortChange"
    >
      <template slot-scope="{ row }" slot="shortId">
        <div>
          <div><a href="javascript: void(0)" style="text-decoration: underline;" @click="onCreativelick(row)">{{ row.shortId }}</a></div>
        </div>
      </template>
      <template slot-scope="{ row }" slot="creativeUrl">
        <div @click="handleMediaPreview(row)">
          <img
            v-show="dialogType(row.creativeUrl) == 'image'"
            width="100%"
            :src="row.creativeUrl"
          />
          <video
            v-show="dialogType(row.creativeUrl) == 'video'"
            :src="row.creativeUrl"
            style="width: 100%"
          ></video>
        </div>
      </template>
      <template slot-scope="{ row }" slot="designer">
        <div>
          {{ designerChange(row) }}
        </div>
      </template>
      <template slot-scope="{ row }" slot="ads">
        <div>
          {{ countAds(row) }}
        </div>
      </template>
      <template slot-scope="{ row }" slot="ctr">
        <div>{{ row.ctr }}%</div>
      </template>
      <template slot-scope="{ row }" slot="cvr">
        <div>{{ row.cvr }}%</div>
      </template>
      <template slot-scope="{ row }" slot="onlineStatus">
        <el-tag type="danger" v-if="row.status !== 2 && row.onlineStatus === 1">违规</el-tag>
        <el-tag type="success" v-else-if="row.onlineStatus === 1">在线</el-tag>
        <el-tag type="info" v-else>未在线</el-tag>
      </template>
    </avue-crud>

    <el-dialog
      title="预览"
      :visible="mediaPreviewDialog.dialogVisible"
      width="80%"
      :modal-append-to-body="false"
      top="0px;"
      :close-on-click-modal="false"
      :before-close="
        () => {
          mediaPreviewDialog.dialogVisible = false;
          if(mediaPreviewDialog.dialogType === 'video') {
            this.$refs.video.pause()
          }
        }
      "
      :append-to-body="true"
      style="text-align: center"
    >
      <img
        v-if="mediaPreviewDialog.dialogType === 'image'"
        :style="previewStyle()"
        :src="mediaPreviewDialog.previewUrl"
      />
      <video
        ref="video"
        v-if="mediaPreviewDialog.dialogType === 'video'"
        :src="mediaPreviewDialog.previewUrl"
        :style="previewStyle()"
        controls="controls"
      ></video>
    </el-dialog>


    <el-dialog
      :title="'素材：' + creativeInfoDialog.name"
      :visible="creativeInfoDialog.dialogVisible"
      width="80%"
      :modal-append-to-body="false"
      top="0px;"
      :close-on-click-modal="false"
      :append-to-body="true"
      style="text-align: center"
      :before-close="
        () => {
        creativeInfoDialog.dialogVisible = false;
        }
      "
    >
      <creative-info v-if="creativeInfoDialog.dialogVisible" :creative-id="creativeInfoDialog.creativeId"></creative-info>
    </el-dialog>
  </basic-container>
</template>

<script>
import {
  add,
  getDesignerList,
  getDetail,
  getTagsCreativeList,
  getSubmitter,
  remove,
  update,
} from "@/api/offer/creativeperformance";
import {getDetail as getOfferDetail} from "@/api/business/offer";
import {getOutList} from '@/api/business/share'
import { getSysDictList } from "@/api/system/dict";
import { mapGetters } from "vuex";
import Moment from "moment";
import creativeInfo from "./creativeInfo";

export default {
  name: 'creativePerformanceOnTag',
  components: {
    creativeInfo
  },
  props: {
    params: {
      type: Object,
    },
    tags: {
      type: String,
    }
  },
  data() {
    return {
      offer: '',
      resultList: [],
      designerList: [],
      agencyTenantList: [],
      submitterList: [],
      platformList: [],
      form: {
        platform: null,
        createUser: null,
        agencyTenantId: '',
        agencyTenantIdList: [],
        beginDate: null,
        endDate: null,
        name: null,
      },
      value1: [],
      query: {
        offerId: "",
        creativeId: "",
      },
      loading: true,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0,
      },
      selectionList: [],
      option: {
        calcHeight: 30,
        tip: false,
        border: true,
        index: true,
        selection: false,
        addBtn: false,
        menu: false,
        menuLeft: false,
        columnBtn: false,
        refreshBtn: false,
        dialogClickModal: false,
        column: [
          {
            label: "短ID",
            prop: "shortId",
            slot: true,
          },
          {
            label: "素材",
            prop: "creativeUrl",
            slot: true,
          },
          {
            label: "类型",
            prop: "type",
            dicData: [
              { label: "图片", value: 0 },
              { label: "视频", value: 1 },
            ],
            slot: true,
          },
          {
            label: "名称",
            prop: "name",
            rules: [
              {
                required: true,
                message: "请输入",
                trigger: "blur",
              },
            ],
          },
          {
            label: "状态",
            prop: "onlineStatus",
            dicData: [
              { label: "未在线", value: 0 },
              { label: "在线", value: 1 },
            ],
            slot: true,
          },
          {
            label: "设计者",
            prop: "designer",
            rules: [
              {
                required: true,
                message: "请输入",
                trigger: "blur",
              },
            ],
            slot: true,
            hide: true,
          },
          {
            label: "代理商",
            prop: "agencyTenantName",
            hide: true,
          },
          {
            label: "在线天数",
            prop: "onlineDays",
            rules: [
              {
                required: true,
                message: "请输入",
                trigger: "blur",
              },
            ],
            sortable: 'custom',
          },
          {
            label: "关联广告数",
            prop: "ads",
            rules: [
              {
                required: true,
                message: "请输入",
                trigger: "blur",
              },
            ],
            sortable: 'custom',
          },
          {
            label: "总消耗",
            prop: "allExpend",
            rules: [
              {
                required: true,
                trigger: "blur",
              },
            ],
            sortable: 'custom',
          },
          {
            label: "Impressions",
            prop: "impressions",
            rules: [
              {
                required: true,
                trigger: "blur",
              },
            ],
            width:120,
            sortable: 'custom',
          },
          {
            label: "Clicks",
            prop: "clicks",
            rules: [
              {
                required: true,
                trigger: "blur",
              },
            ],
            sortable: 'custom',
          },
          {
            label: "CTR",
            prop: "ctr",
            rules: [
              {
                required: true,
                trigger: "blur",
              },
            ],
            slot: true,
            sortable: 'custom',
          },
          {
            label: "Install",
            prop: "install",
            rules: [
              {
                required: true,
                trigger: "blur",
              },
            ],
            sortable: 'custom',
          },
          {
            label: "CVR",
            prop: "cvr",
            rules: [
              {
                required: true,
                message: "请输入CVR",
                trigger: "blur",
              },
            ],
            slot: true,
            sortable: 'custom',
          },
        ],
      },
      data: [],
      sortList: [],
      mediaPreviewDialog: {
        dialogVisible: false,
        dialogType: "image", //image or video
        previewUrl: "",
      },
      creativeInfoDialog: {
        dialogVisible: false,
        creativeId: '',
      },
      isAdvSharedOffer: false,
    };
  },
  computed: {
    ...mapGetters([ "userInfo"]),
  },
  watch: {
  },
  created() {
    this.offer = this.params.offer;
    let lastWeek = this.params.startDate;
    let now = this.params.endDate;
    this.value1 = [lastWeek, now];

    let self = this;

    this.refresh();
    if (this.$route.query.creativeId) {
      this.value1[0] = this.$route.query.beginDate;
      this.value1[1] = this.$route.query.endDate;
      this.query.creativeId = this.$route.query.creativeId;
      this.onLoad(this.page, {});
    }
    self.updateIsAdvSharedOffer();
  },
  methods: {
    isShowSelectOptions(isShowSelectOptions){
      if(!isShowSelectOptions) this.$refs.performTime.blur();
      if(!isShowSelectOptions) this.$refs.performPlatform.blur();
    },
    previewStyle() {
      let height = window.innerHeight < 300 ? 300 : window.innerHeight - 160;
      return {
        maxWidth: "100%",
        maxHeight: height + "px",
      };
    },
    handleMediaPreview(row) {
      this.mediaPreviewDialog.previewUrl = row.creativeUrl + "?" + (row.updateTime ? row.updateTime.replace(/[ :-]*/gi, "") : 1234);
      this.mediaPreviewDialog.dialogType = row.type == 0 ? "image" : "video";
      this.mediaPreviewDialog.dialogVisible = true;
    },
    /**
     * 图片排序
     * @param val
     */
    sortChange(val) {
      let prop = val.prop;
      let orderBy = null;
      if (val.order === "descending") {
        orderBy = 'desc';
        //向上排序
      } else if (val.order === "ascending") {
        orderBy = 'asc';
        //不排序
      }
      if(orderBy != null) {
        this.sortList = [{name: prop, orderBy: orderBy}];
      } else {
        this.sortList = [];
      }
      this.onLoad(this.page);
    },
    setIsAdvSharedOfferChanged(val) {
      let self = this;
      self.isAdvSharedOffer = val;
      self.form.createUser = null;
      self.form.agencyTenantId = '';
      self.form.agencyTenantIdList = [];
      let column = self.findObject(self.option.column,'designer');
      if(column && column != -1) {
        column.hide = self.isAdvSharedOffer;
      }
      column = self.findObject(self.option.column,'agencyTenantName');
      if(column && column != -1) {
        column.hide = !self.isAdvSharedOffer;
      }
      if(self.isAdvSharedOffer) {
        self.getAgencyTenantList();
      }
    },
    updateIsAdvSharedOffer() {
      let self = this;
      if(self.userInfo.is_agency == 0) {
        self.loadOfferInfo(self.offer,(offerInfo)=>{
          if(offerInfo) {
            self.setIsAdvSharedOfferChanged(offerInfo.isShared == 1);
          } else {
            self.setIsAdvSharedOfferChanged(false);
          }
        });
      } else {
        self.setIsAdvSharedOfferChanged(false);
      }
    },
    loadOfferInfo(offerId,success) {
      if(offerId != null && offerId != '' && success) {
        getOfferDetail(offerId).then((res)=>{
          success(res.data.data);
        }).catch(()=>{
          success(null);
        });
      }
    },
    getAgencyTenantList() {
      getOutList(
        1,
        100,
        {offerId: this.offer},
      ).then(res => {
        this.agencyTenantList = res.data.data.records
      })
    },
    refresh() {
      //refresh开始，这样写避免代码迁移太多
      /**
       * 调用设计师的字典
       * @type {string}
       */
      this.query.creativeId = null;
      this.query.offerId = this.offer;
      getDesignerList(this.offer).then((res) => {
        this.designerList = res.data.data;
      });
      getSysDictList("platforms").then((map) => {
        this.platformList = map['platforms']
      });
      getSubmitter(this.offer).then((res) => {
        this.submitterList = res.data.data;
      });
    },
    /**
     * 用来转换设计师id （方法）
     */
    designerChange(row) {
      let designers = row.designer.split(",");
      let designerList = this.designerList;
      let name = [];
      for (let i in designerList) {
        let designerId = designerList[i].id;
        let designerName = designerList[i].realName;
        for (let j in designers) {
          let designer = designers[j];
          if (designer === designerId) {
            name.push(designerName);
          }
        }
      }
      return name.join(",");
    },
    /**
     * 统计当前素材跑了多少个广告
     * @param row
     * @returns {string}
     */
    countAds(row) {
      let adsArr = row.ads.split(",");
      let res = [...new Set(adsArr)];
      return res.length;
    },
    submitForm() {
      if (this.value1 != null) {
        this.form.beginDate = this.value1[0];
        this.form.endDate = this.value1[1];
      } else {
        this.form.beginDate = "";
        this.form.endDate = "";
      }
      this.onLoad(this.page, this.form);
    },
    resetSearch() {
      this.form = {
        createUser: null,
        platform: null,
        agencyTenantId: '',
        agencyTenantIdList: [],
        beginDate: "",
        endDate: "",
        name: '',
      };
      this.query.creativeId = null;
      this.value1 = [];
      this.onLoad(this.page, this.form);
    },
    dialogType(val) {
      let type;
      let urlTail = val.split(".")[val.split(".").length - 1];
      let imgList = ["jpg", "jpeg", "png", "gif", "bmp"];
      let videoList = ["mp4", "mov", "avi", "mp3", "ogg", "rmvb", "mkv"];
      if (imgList.includes(urlTail)) {
        type = "image";
      } else if (videoList.includes(urlTail)) {
        type = "video";
      }
      return type;
    },

    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      if (this.value1 != null) {
        this.form.beginDate = this.value1[0];
        this.form.endDate = this.value1[1];
      } else {
        this.form.beginDate = "";
        this.form.endDate = "";
      }
      this.form.agencyTenantId = this.form.agencyTenantIdList.join(',');
      this.query.offerId = this.offer;
      let sortList = this.sortList;
      getTagsCreativeList(
        this.page.currentPage,
        this.page.pageSize,
        Object.assign({tags: this.params.tags}, params, this.query, this.form, {sortList: JSON.stringify(sortList)})
      ).then((res) => {
        let data = res.data.data;
        this.page.total = data.total;
        this.resultList = res.data.data;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    },
    onCreativelick(row) {
      let self = this;
      self.$nextTick(() => {
        self.creativeInfoDialog.name = row.name;
        self.creativeInfoDialog.creativeId = row.id;
        self.creativeInfoDialog.dialogVisible = true;
      });
    },
  },
};
</script>

<style>
</style>
